import { _decorator, Animation, Component, Node, Prefab, resources, instantiate, find, AnimationClip, tween, Vec3, UIOpacity } from 'cc';
const { ccclass, property } = _decorator;
import { UserGlobal } from '../Globals/UserGlobal';
import { HttpManager } from '../Utils/HttpManager';
import { UiManager } from './UiManager';

@ccclass('SprinklerManager')
export class SprinklerManager extends Component {
    @property({ type: Node })
    public coinNode: Node | null = null;
    @property({ type: AnimationClip })
    public zoomAnimation: AnimationClip | null = null;
    @property({ type: Node })
    public landNode: Node | null = null;
    @property({ type: Prefab })
    public rainPrfb: Prefab | null = null;

    private status: number = 5;
    start() {
        HttpManager.get('/game/api/water', { user_id: UserGlobal.instance._userId }, (response) => {
            if (('data' in response) && ('status' in response.data)) {
                if (response.data.status == 0) {
                    this.status = 0;
                } else if (response.data.status == 1) {
                    this.status = 1;
                } else if (response.data.status == 2) {
                    this.status = 2;
                } else if (response.data.status == 3) {
                    this.status = 3;
                } else if (response.data.status == 4) {
                    this.status = 4;
                } else {
                    this.status = 5;
                }
            }
        }, (response) => {
            let msg = ('message' in response) ? response.message : '获取浇水任务状态错误';
            UiManager.showToast(msg, 1);
        });

        this.node.on(Node.EventType.TOUCH_START, this.onSprinklerClicked, this);
    }

    onSprinklerClicked() {
        if (this.status == 1) {
            UiManager.showToast('不在可撒水时间，请稍后再来！');
            return;
        } else if (this.status == 2) {
            UiManager.showToast('您还没有认养石斛！');
            return;
        } else if (this.status == 3) {
            UiManager.showToast('抱歉，您还没有洒水车！请先提货以激活洒水车');
            return;
        } else if (this.status == 4) {
            UiManager.showToast('今日任务已完成，明天再来');
            return;
        } else if (this.status == 5) {
            UiManager.showToast('出错了，请联系平台客服');
            return;
        }
        if (UserGlobal.instance._sprinklerNumber <= 0) {
            UiManager.showToast('抱歉，您还没有洒水车！请先提货以激活洒水车。');
            return;
        }

        let self = this;
        resources.load('Prefabs/sprinkler/' + UserGlobal.instance._sprinklerNumber, Prefab, function (err, prefab: Prefab) {
            if (err) {
                console.log('载入洒水车预制资源失败,原因:' + err);
                return;
            }

            let _pos1 = self.node.worldPosition;
            let sprinkler = instantiate(prefab);
            let animation = sprinkler.addComponent(Animation);
            sprinkler.setScale(new Vec3(0.33, 0.33));
            tween(sprinkler).to(0.1, ({
                worldPosition: new Vec3(_pos1.x - 196, 0 - _pos1.y - 64)
            }), { easing: 'smooth' }).call(() => {
                find('Canvas').addChild(sprinkler);
                self.node.active = false;

                tween(sprinkler).to(2, ({
                    position: new Vec3(0, 0),
                    scale: new Vec3(1, 1)
                }), ({ easing: 'smooth' })).call(() => {
                    animation.addClip(self.zoomAnimation, 'zoom');
                    animation.defaultClip = self.zoomAnimation;
                    animation.play();

                    setTimeout(() => {
                        tween(sprinkler).to(3, ({
                            position: new Vec3(_pos1.x - 196, 0 - _pos1.y - 64),
                            scale: new Vec3(0.33, 0.33)
                        }), ({ easing: 'smooth' })).call(() => {
                            sprinkler.destroy();
                            self.node.active = true;
                        }).start();
                    }, 4000);
                }).start();
            }).start();

            setTimeout(() => {
                let land = self.landNode.children;
                for (let i = 0; i < land.length; i++) {
                    let _land = land[i].children;
                    let _isExistTree = false;
                    for (let j = 0; j < _land.length; j++) {
                        if (_land[j].name == 'tree') {
                            _isExistTree = true;
                            break;
                        }
                    }
                    if (_isExistTree == false) {
                        continue;
                    }

                    for (let j = 0; j < UserGlobal.instance._sprinklerNumber; j++) {
                        setTimeout(() => {
                            let _rain = instantiate(self.rainPrfb);
                            _rain.setPosition(0, 120);
                            tween(_rain).to(1, ({
                                position: new Vec3(0, 10),
                                scale: new Vec3(0.02, 0.02)
                            })).call(() => {
                                let _opacity = _rain.addComponent(UIOpacity);
                                _opacity.opacity = 255;
                                tween(_opacity).to(0.2, ({ opacity: 0 })).call(() => {
                                    _rain.destroy();
                                }).start();
                            }).start();
                            land[i].addChild(_rain);
                        }, j * 1000);
                    }
                }
            }, 9000);
        });

        let _timeout = 9000;
        _timeout += UserGlobal.instance._sprinklerNumber * 1000;
        setTimeout(() => {
            HttpManager.post('/game/api/water', { user_id: UserGlobal.instance._userId }, (response) => {
                let _child = this.coinNode.children;
                for (let i = 0; i < _child.length; i++) {
                    _child[i].active = true;
                }
                this.status = 4;
            }, (response) => {
                let msg = ('message' in response) ? response.message : '出错了';
                UiManager.showToast(msg, 1);
            });
        }, _timeout);
    }
}
